package com.example.fourm.exception;

import com.example.fourm.common.AppResult;
import com.example.fourm.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationException(ApplicationException e) {
        e.printStackTrace(); //打印异常
        log.error(e.getMessage()); //记录日志
        if(e.getErrorResult()!=null){
            return e.getErrorResult();
        }
        //非空校验
         if(e.getMessage() == null || "".equals(e.getMessage())){
             return AppResult.failure(ResultCode.ERROR_SERVICES);
         }
        return AppResult.failure(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exception(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        //非空校验
        if(e.getMessage() == null || "".equals(e.getMessage())){
            return AppResult.failure(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failure(e.getMessage());
    }
}
